﻿namespace CodeProject.Podium.WP7
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media.Imaging;
    using System.Xml.Linq;
    using Microsoft.Phone.Controls;

    public partial class MainPage : PhoneApplicationPage
    {
        PushNotifier notifier;

        public MainPage()
        {
            InitializeComponent();
        }

        private void PreviousButton_Click(object sender, EventArgs e)
        {
            PreviousSlide();
        }

        private void NextButton_Click(object sender, EventArgs e)
        {
            NextSlide();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            notifier = new PushNotifier("PodiumChannel", "PodiumService");
            notifier.Subscribed += new EventHandler(notifier_SubscribeToService);
            notifier.HttpNotificationReceived += new EventHandler<Microsoft.Phone.Notification.HttpNotificationEventArgs>(notifier_HttpNotificationReceived);
            notifier.Open();
        }

        void notifier_HttpNotificationReceived(object sender, Microsoft.Phone.Notification.HttpNotificationEventArgs e)
        {
            XDocument document;

            using (var reader = new StreamReader(e.Notification.Body))
            {
                string payload = reader.ReadToEnd().Replace('\0',
                  ' ');
                document = XDocument.Parse(payload);
            }

            string slide = (from c in document.Descendants("SlideUpdate")
                            select c.Element("Slide").Value).FirstOrDefault();

            if (string.IsNullOrEmpty(slide))
            {
                Dispatcher.BeginInvoke(() =>
                {
                    this.LayoutRoot.Children.Clear();
                    this.LayoutRoot.Children.Add(new ReadyForAction());
                });
            }
            else
            {
                GetSlide(new Guid(slide));
            }
        }

        void notifier_SubscribeToService(object sender, EventArgs e)
        {
            Register(notifier.GetHttpChannel().ChannelUri);
        }

        #region Service

        void Register(Uri uri)
        {
            var httpChannel = notifier.GetHttpChannel();

            string baseUri = "http://localhost:8000/RegirstatorService/Register?uri={0}";
            string theUri = String.Format(baseUri, uri.ToString());
            WebClient client = new WebClient();
            client.DownloadStringCompleted += (s, ev) =>
            {
            };
            client.DownloadStringAsync(new Uri(theUri));
        }

        void GetSlide(Guid guid)
        {
            string baseUri = "http://localhost:8000/RegirstatorService/GetSlide?guid={0}";
            string theUri = String.Format(baseUri, guid.ToString());
            WebClient client = new WebClient();
            client.DownloadStringCompleted += (s, ev) =>
            {
                XDocument xml = XDocument.Parse(ev.Result);
                string mime = xml.Root.Value;

                var results = Convert.FromBase64String(mime);

                Dispatcher.BeginInvoke(() =>
                {
                    MemoryStream stream = new MemoryStream(results.Length);
                    stream.Write(results, 0, results.Length);
                    BitmapImage image = new BitmapImage();
                    image.SetSource(stream);

                    this.LayoutRoot.Children.Clear();
                    this.LayoutRoot.Children.Add(new Image() { Source = image });
                });
            };
            client.DownloadStringAsync(new Uri(theUri));
        }

        void NextSlide()
        {
            string uri = "http://localhost:8000/RegirstatorService/NextSlide";
            WebClient client = new WebClient();
            client.DownloadStringCompleted += (s, ev) =>
            {
            };
            client.DownloadStringAsync(new Uri(uri));
        }

        void PreviousSlide()
        {
            string uri = "http://localhost:8000/RegirstatorService/PreviousSlide";
            WebClient client = new WebClient();
            client.DownloadStringCompleted += (s, ev) =>
            {
            };
            client.DownloadStringAsync(new Uri(uri));
        }

        #endregion

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            NextSlide();
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            PreviousSlide();
        }

        private void GestureListener_Flick(object sender, FlickGestureEventArgs e)
        {

        }

        private void GestureListener_Tap(object sender, GestureEventArgs e)
        {
            NextSlide();
        }

        private void GestureListener_DoubleTap(object sender, GestureEventArgs e)
        {
            NextSlide();
        }

        private void PhoneApplicationPage_Unloaded(object sender, RoutedEventArgs e)
        {
            notifier.Close();
        }

        private void DebugButton_Click(object sender, EventArgs e)
        {

        }

        private void AboutButton_Click(object sender, EventArgs e)
        {

        }
    }
}